package org.book.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.book.dao.AdminBean;
import org.book.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		LoginService loginService = new LoginService();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		AdminBean admin = new AdminBean(username,password);
		
		String flag = request.getParameter("flag");
		
		
		//登录
		if("1".equals(flag)) {
			if(loginService.loginTest(admin)) {
				request.setAttribute("username", username);
				request.getRequestDispatcher("pages/user/login_success.jsp").forward(request, response);
			}else {
				response.getWriter().print("登陆失败");
			}
		}
		//注册
		else if("0".equals(flag)){
			if(loginService.registTest(admin)) {
				request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);
			}else {
				response.getWriter().print("注册失败");
			}
		}else {
			request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);
		}
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
